import React, { useState, useEffect } from 'react';
import {Modal, Checkbox, Form, Button, message} from 'antd';
import axiosInstance from "../../../component/axiosInstance.jsx";

const RoleModal = ({ visible, onClose, onOk, userId, initialRoles }) => {
    const [roles, setRoles] = useState([]);
    const [selectedRoles, setSelectedRoles] = useState(initialRoles);

    useEffect(() => {
        // 假设这里有一个 API 可以获取所有的角色
        axiosInstance.get('/api/roles/get-all-roles-with-permissions')
            .then(response => {
                if (response.status === 200) {
                    const data = response.data.data;
                    setRoles(data);
                    // 初始化选中的角色
                    setSelectedRoles(initialRoles || []);
                } else {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
            })
            .catch(error => {
                console.error('获取角色失败：', error);
                message.error('获取角色失败，请稍后再试！');
            });
    }, [initialRoles]);

    const handleRoleChange = (roleId) => {
        if (selectedRoles.includes(roleId)) {
            setSelectedRoles(selectedRoles.filter(id => id !== roleId));
        } else {
            setSelectedRoles([...selectedRoles, roleId]);
        }
    };

    const handleSubmit = () => {
        if (JSON.stringify(selectedRoles.sort()) === JSON.stringify(initialRoles.sort())) {
            onClose();
        } else {
            onOk(selectedRoles);
            onClose();
        }
    };

    return (
        <Modal
            title="修改用户角色"
            visible={visible}
            onCancel={onClose}
            okText="提交"
            cancelText="取消"
            width={400}
            footer={[
                <div key="footer" style={{ display: 'flex', justifyContent: 'center' }}>
                    <Button key="cancel" onClick={onClose} style={{ marginRight: 8 }}>
                        取消
                    </Button>
                    <Button key="submit" type="primary" onClick={handleSubmit}>
                        提交
                    </Button>
                </div>
            ]}
        >
            <Form>
                {roles.map(role => (
                    <Form.Item key={role.roleId} style={{ marginBottom: 0 }}>
                        <Checkbox
                            checked={selectedRoles.includes(role.roleId)}
                            onChange={() => handleRoleChange(role.roleId)}
                        >
                            <p>{role.roleName}</p>
                        </Checkbox>
                    </Form.Item>
                ))}
            </Form>
        </Modal>
    );
};

export default RoleModal;